const User = require('../proxy').User;
const TopicCollect = require('../proxy').TopicCollect;
const fs = require('fs');
const formidable = require('formidable');
const Topic = require('../proxy').Topic;
const Reply = require('../proxy').Reply;
const utility = require('utility');
const util = require('util');
const Response = require('../common/Response');
const tools = require('../common/tools');
const config = require('../config');
const EventProxy = require('eventproxy');
const validator = require('validator');
const _ = require('lodash');

//首页
exports.index = function(req, res, next) {
    let user_name = req.params.name;

    User.getUserByLoginName(user_name, function (err, user) {
       if(err) {
           return next(err);
       }
       if (!user) {
           let response = new Response(0, '', '这个用户不存在');
           res.send(response);
           return;
       }

        let response = new Response(1, user, '');
        res.send(response);
    });
};

//根据_id查找用户信息
exports.getUserById = function (req, res, next) {
    let user_id = req.query.user_id;

    User.getUserById(user_id, function (err, user) {
        if(err) {
            return next(err);
        }
        if (!user) {
            let response = new Response(0, '', '这个用户不存在');
            res.send(response);
            return;
        }

        let response = new Response(1, user, '');
        res.send(response);
    })
};

//根据loginName查找用户信息
exports.getUserByName = function (req, res, next) {

    let loginName = req.query.loginName;

    User.getUserByName(loginName, function (err, user) {
        if(err) {
            return next(err);
        }
        if (!user) {
            let response = new Response(0, '', '这个用户不存在');
            res.send(response);
            return;
        }

        let response = new Response(1, user, '');
        res.send(response);
    })
};

//查找用户
exports.getUser = function (req, res, next) {

    let query = req.query;

    User.getUser(query, {}, function (err, user) {
        if(err) {
            return next(err);
        }
        if (!user) {
            let response = new Response(0, '', '这个用户不存在');
            res.send(response);
            return;
        }

        let response = new Response(1, user, '');
        res.send(response);
    })
};

//用户收藏的话题列表
exports.listCollectedTopics = function (req, res, next) {
    let name = req.query.loginName;
    // let page = Number(req.query.page) || 1;
    // let limit = config.list_topic_count;

    User.getUserByLoginName(name, function (err, user) {
        if(err || !user) {
            return next(err);
        }

        // let pages = Math.ceil(user.collect_topic_count / limit);

        let opt = {
            // skip: (page - 1) * limit,
            // limit: limit,
        };

        TopicCollect.getTopicCollectByUserId(user._id, opt, function (err, docs) {
            if(err) {
                return next(err);
            }

            let ids = docs.map(function (doc) {
                return String(doc.topic_id)
            });

            let query = { _id: { '$in': ids }};
            Topic.getTopicsByQuery(query, {}, function (topics) {
                topics = _.sortBy(topics, function (topic) {
                    return ids.indexOf(String(topic._id));
                });

                let response = new Response(1, topics, '');
                res.json(response);
            })
        })
    })
};

//用户参与回复的列表
exports.listReplies = function (req, res, next) {
    let user_name = req.query.loginName;
    let page = Number(req.query.page) || 1;
    let limit = 5;

    if(Number(req.query.page)) {
        limit = config.list_topic_count
    }

    let options = {
        skip: (page - 1) * limit,
        limit: limit,
        sort: '-update_at'
    };

    User.getUserByLoginName(user_name, function (err, user) {
        if(err) {
            return next(err);
        }
        if(!user) {
            let response = new Response(0, '', '查无此人');
            res.json(response);
        }

        let opt = {
            skip: (page - 1) * limit,
            limit: limit,
        };

        Reply.getRepliesByUserId(user._id, opt, function (err, replies) {
            if(err) {
                return next(err);
            }
            if(!replies) {
                let response = new Response(0, [], '暂无参与话题的评论');
                res.json(response);
            }
            //获取所有评论的_id
            let topic_ids = replies.map(function (reply) {
                return reply.topic_id.toString();
            });
            topic_ids = _.uniq(topic_ids);

            let query = {'_id': {'$in': topic_ids}};
            let opt = {};
            Topic.getTopicsByQuery(query, opt, function (topics) {
                topics = _.sortBy(topics, function (topic) {
                    return topic_ids.indexOf(topic._id.toString());
                });

                let response = new Response(1, topics, '');
                res.json(response);
            })
        })
    })
};

//更新用户信息
exports.updateInfo = function (req, res, next) {
    let sex = req.body.sex || '';
    let love_state = req.body.love_state || '';
    let location = req.body.location || '';
    let signature = req.body.signature || '';
    let url = req.body.url || '';

    //验证信息的正确性
    if([sex, love_state, location, signature, url].every(item => item === '')) {
        let response = new Response(0, '', '至少保存一个信息');
        return res.json(response);
    }

    User.getUserById(req.session.user._id, function (err, user) {
        if(err) {
            return next(err);
        }
        if(!user) {
            let response = new Response(0, '', '查无此人');
            return res.json(response);
        }

        user.sex = sex;
        user.love_state = love_state;
        user.location = location;
        user.signature = signature;
        user.url = url;
        user.save(function (err) {
            if(err) {
                return next(err);
            }

            let response = new Response(1, '', '保存成功');
            res.json(response);
        })
    })
};

//上传头像
exports.uploadAvatar = function (req, res, next) {
    let form = new formidable.IncomingForm();
    form.encoding = 'utf-8'; // 编码
    form.keepExtensions = true; // 保留扩展名
    form.maxFieldsSize = 2 * 1024 * 1024; // 文件大小
    // form.uploadDir = 'C:/wpw/keng/keng-node/public/images/';  // 存储路径
    form.parse(req, function(err, fileds, files){ // 解析 formData数据
        if(err){ return console.log('error', err) }

        console.log('-----', files);
        //单张图片上传
        let imgName = files.image.name; // 修改之后的名字
        let data = fs.readFileSync(files.image.path); // 同步读取文件

        fs.writeFile('../images/avatar/' + imgName, data, function(err){ // 存储文件
            if(err){
                let response = new Response(0, '', '上传图片失败');
                res.json(response);
                return console.log(err)
            }

            let url = 'http://47.93.192.82/images/avatar/' + imgName;

            User.getUserById(req.session.user._id, function (err, user) {
                if(err) {
                    return next(err);
                }
                if(!user) {
                    let response = new Response(0, '', '查无此人');
                    return res.json(response);
                }

                user.avatar = url;
                user.save(function (err) {
                    if(err) {
                        return next(err);
                    }
                })
            });

            let query = {
              author_name: req.session.user.name
            };
            Topic.getTopicsByQuery(query, {}, function (topic) {
                topic.map(function (item) {
                    item.avatar = url;
                    item.save(function (err) {
                        if (err) {
                            return next(err);
                        }
                    })
                })
            });

            let response = new Response(1, url, '上传成功！');
            res.json(response);
        })
    })
};